package com.zkjd.lingdong.ui.pairing

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.widget.Toast
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.BluetoothSearching
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import com.zkjd.lingdong.bluetooth.ScanState
import com.zkjd.lingdong.ui.component.BluetoothPermissionRequest
import timber.log.Timber

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PairingScreen(
    navController: NavController,
    viewModel: PairingViewModel = hiltViewModel()
) {
    // 使用蓝牙权限请求组件包装整个屏幕
    BluetoothPermissionRequest(
        content = {
            PairingScreenContent(navController, viewModel)
        },
        onPermissionResult = { granted ->
            if (granted) {
                // 权限授予成功，检查蓝牙状态
                viewModel.checkBluetoothStatus()
            } else {
                // 权限被拒绝，通知用户
                viewModel.onPermissionDenied()
            }
        }
    )
}

@SuppressLint("MissingPermission")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PairingScreenContent(
    navController: NavController,
    viewModel: PairingViewModel
) {
    val context = LocalContext.current
    val scanState by viewModel.scanState.collectAsState()
    val currentStep by viewModel.currentStep.collectAsState()
    val isBluetoothEnabled by viewModel.isBluetoothEnabled.collectAsState()
    val pairingDevice by viewModel.pairingDevice.collectAsState()
    val isPairingSuccessful by viewModel.isPairingSuccessful.collectAsState()
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    
    // 监听UI事件
    LaunchedEffect(key1 = true) {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiEvents.collect { event ->
                when (event) {
                    is PairingViewModel.UiEvent.ShowError -> {
                        Toast.makeText(context, event.message, Toast.LENGTH_SHORT).show()
                        Timber.d("配对错误: ${event.message}")
                    }
                    is PairingViewModel.UiEvent.ShowToast -> {
                        Toast.makeText(context, event.message, Toast.LENGTH_SHORT).show()
                        Timber.d("配对提示: ${event.message}")
                    }
                    is PairingViewModel.UiEvent.PairingSuccess -> {
                        viewModel.addDeviceToDb()
                        Toast.makeText(context, "配对成功！", Toast.LENGTH_SHORT).show()
                        Timber.d("配对成功: ${event.macAddress}")
                    }
                    is PairingViewModel.UiEvent.PairingFailed -> {
                        Toast.makeText(context, "配对失败: ${event.reason}", Toast.LENGTH_SHORT).show()
                        Timber.d("配对失败: ${event.reason}")
                    }
                    is PairingViewModel.UiEvent.RequestBluetoothEnable -> {
                        // 提示用户打开蓝牙
                        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        context.startActivity(enableBtIntent)
                    }
                }
            }
        }
    }
    
    // 监听配对步骤变化
    LaunchedEffect(currentStep) {
        Timber.d("配对步骤已更新: $currentStep")
    }
    
    // 监听配对成功状态
    LaunchedEffect(isPairingSuccessful) {
        if (isPairingSuccessful) {
            Timber.d("配对标记为成功")
        }
    }
    
    // 检查蓝牙状态变化
    LaunchedEffect(isBluetoothEnabled) {
        if (isBluetoothEnabled){// && currentStep == PairStep.STEP_ONE_CHECK_BLUETOOTH) {
            viewModel.startPairingProcess()
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("设备配对") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF1C1C28),//MaterialTheme.colorScheme.primary,
                    titleContentColor = Color(0xFFFFFFFF),//MaterialTheme.colorScheme.onPrimary
                ),
                navigationIcon = {
                    IconButton(onClick = {
                        viewModel.stopScan()
                        navController.popBackStack()
                    }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回",
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier=Modifier.size(55.dp)
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(MaterialTheme.colorScheme.background)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 显示进度指示器
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                StepIndicator(
                    step = 1,
                    title = "检查蓝牙",
                    isActive = currentStep == PairStep.STEP_ONE_CHECK_BLUETOOTH,
                    isCompleted = currentStep.ordinal > PairStep.STEP_ONE_CHECK_BLUETOOTH.ordinal
                )
                
                Spacer(
                    modifier = Modifier
                        .weight(1f)
                        .height(1.dp)
                        .background(MaterialTheme.colorScheme.surfaceVariant)
                )
                
                StepIndicator(
                    step = 2,
                    title = "扫描设备",
                    isActive = currentStep == PairStep.STEP_TWO_SCANNING,
                    isCompleted = currentStep.ordinal > PairStep.STEP_TWO_SCANNING.ordinal
                )
                
                Spacer(
                    modifier = Modifier
                        .weight(1f)
                        .height(1.dp)
                        .background(MaterialTheme.colorScheme.surfaceVariant)
                )
                
                StepIndicator(
                    step = 3,
                    title = "配对完成",
                    isActive = currentStep == PairStep.STEP_THREE_PAIRED,
                    isCompleted = false
                )
            }
            
            // 根据当前步骤显示不同内容
            when (currentStep) {
                PairStep.STEP_ONE_CHECK_BLUETOOTH -> {
                    BluetoothCheckStep(
                        isBluetoothEnabled = isBluetoothEnabled,
                        onEnableBluetooth = {
                            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                            context.startActivity(enableBtIntent)

                            Thread.sleep(2000)
                            viewModel.checkBluetoothStatus()
                        },
                        onContinue = {
                            viewModel.startPairingProcess()
                        }
                    )
                }
                
                PairStep.STEP_TWO_SCANNING -> {
                    DeviceScanningStep(
                        scanState = scanState,
                        pairingDevice = pairingDevice,
                        onRetry = {
                            viewModel.startScan()
                        }
                    )
                }
                
                PairStep.STEP_THREE_PAIRED -> {
                    PairingCompleteStep(
                        deviceName = pairingDevice?.name ?: "设备",
                        deviceAddress = pairingDevice?.address ?: "",
                        onFinish = {
                            navController.popBackStack()
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun StepIndicator(
    step: Int,
    title: String,
    isActive: Boolean,
    isCompleted: Boolean
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.width(80.dp)
    ) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .size(32.dp)
                .background(
                    color = when {
                        isCompleted -> MaterialTheme.colorScheme.primary
                        isActive -> MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
                        else -> MaterialTheme.colorScheme.surfaceVariant
                    },
                    shape = CircleShape
                )
        ) {
            if (isCompleted) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onPrimary,
                    modifier = Modifier.size(20.dp)
                )
            } else {
                Text(
                    text = step.toString(),
                    color = if (isActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = title,
            style = MaterialTheme.typography.bodySmall,
            color = if (isActive || isCompleted) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
fun BluetoothCheckStep(
    isBluetoothEnabled: Boolean,
    onEnableBluetooth: () -> Unit,
    onContinue: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Spacer(modifier = Modifier.height(40.dp))
        
        // 蓝牙图标
        Icon(
            imageVector = Icons.Default.Bluetooth,
            contentDescription = null,
            modifier = Modifier.size(120.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(24.dp))
        
        // 提示文本
        Text(
            text = "第一步：检查蓝牙",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Text(
            text = if (isBluetoothEnabled) 
                "蓝牙已开启，可以继续下一步" 
            else 
                "请开启您车机的蓝牙功能",
            style = MaterialTheme.typography.bodyLarge,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onBackground
        )
        
        Spacer(modifier = Modifier.height(32.dp))
        
        // 操作按钮
        if (isBluetoothEnabled) {
            Button(
                onClick = onContinue,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 32.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Text("继续", modifier = Modifier.padding(vertical = 8.dp))
            }
        } else {
            Button(
                onClick = onEnableBluetooth,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 32.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Text("开启蓝牙", modifier = Modifier.padding(vertical = 8.dp))
            }
        }
    }
}

@SuppressLint("MissingPermission")
@Composable
fun DeviceScanningStep(
    scanState: ScanState,
    pairingDevice: BluetoothDevice?,
    onRetry: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Spacer(modifier = Modifier.height(40.dp))
        
        // 扫描图标或动画
        if (pairingDevice == null) {
            ScanningAnimation()
        } else {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(60.dp),
                    color = MaterialTheme.colorScheme.primary
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Text(
                    text = "正在连接设备...",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
        
        Spacer(modifier = Modifier.height(24.dp))
        
        // 提示文本
        Text(
            text = "第二步：设备配对",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        if (pairingDevice == null) {
            Text(
                text = "请将妥妥贴设备置于配对模式\n并靠近车机1米范围内",
                style = MaterialTheme.typography.bodyLarge,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.onBackground
            )
            
            if (scanState is ScanState.ScanFailed) {
                Spacer(modifier = Modifier.height(16.dp))
                
                Text(
                    text = "扫描失败: ${scanState.reason}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Button(
                    onClick = onRetry,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Text("重新扫描")
                }
            }
        } else {
            Text(
                text = "正在连接设备：${pairingDevice.name ?: "未知设备"}\n" +
                       "地址：${pairingDevice.address}",
                style = MaterialTheme.typography.bodyLarge,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
    }
}

@Composable
fun PairingCompleteStep(
    deviceName: String,
    deviceAddress: String,
    onFinish: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Spacer(modifier = Modifier.height(40.dp))
        
        // 成功图标
        Icon(
            imageVector = Icons.Default.CheckCircle,
            contentDescription = null,
            modifier = Modifier.size(120.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(24.dp))
        
        // 提示文本
        Text(
            text = "第三步：配对完成",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Text(
            text = "您的设备已成功配对！",
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = "设备名称：$deviceName\n设备地址：$deviceAddress",
            style = MaterialTheme.typography.bodyLarge,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onBackground
        )
        
        Spacer(modifier = Modifier.height(32.dp))
        
        Button(
            onClick = onFinish,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 32.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primary
            )
        ) {
            Text("完成", modifier = Modifier.padding(vertical = 8.dp))
        }
    }
}

@Composable
fun ScanningAnimation() {
    Box(contentAlignment = Alignment.Center) {
        val infiniteTransition = rememberInfiniteTransition(label = "scan")
        
        // 外环
        val outerAlpha by infiniteTransition.animateFloat(
            initialValue = 0.7f,
            targetValue = 0f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000, easing = LinearEasing),
                repeatMode = RepeatMode.Restart
            ),
            label = "outerAlpha"
        )
        val outerScale by infiniteTransition.animateFloat(
            initialValue = 1f,
            targetValue = 2f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000, easing = LinearEasing),
                repeatMode = RepeatMode.Restart
            ),
            label = "outerScale"
        )
        
        // 中环
        val middleAlpha by infiniteTransition.animateFloat(
            initialValue = 0.7f,
            targetValue = 0f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000, delayMillis = 400, easing = LinearEasing),
                repeatMode = RepeatMode.Restart
            ),
            label = "middleAlpha"
        )
        val middleScale by infiniteTransition.animateFloat(
            initialValue = 0.8f,
            targetValue = 1.8f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000, delayMillis = 400, easing = LinearEasing),
                repeatMode = RepeatMode.Restart
            ),
            label = "middleScale"
        )
        
        // 动画圆环
        Box(
            modifier = Modifier
                .size(100.dp)
                .scale(outerScale)
                .alpha(outerAlpha)
                .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.5f), CircleShape)
        )
        
        Box(
            modifier = Modifier
                .size(80.dp)
                .scale(middleScale)
                .alpha(middleAlpha)
                .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.5f), CircleShape)
        )
        
        // 中心图标
        Surface(
            modifier = Modifier.size(60.dp),
            shape = CircleShape,
            color = MaterialTheme.colorScheme.primary
        ) {
            Box(contentAlignment = Alignment.Center) {
                Icon(
                    imageVector = Icons.Default.BluetoothSearching,
                    contentDescription = null,
                    modifier = Modifier.size(30.dp),
                    tint = MaterialTheme.colorScheme.onPrimary
                )
            }
        }
    }
} 